<?php
class Ajax {
	function __construct($returnResults = true){
		$controller = F::get()->Controller();
		#Check if function exists and if the function is public
		if( method_exists($this, $controller->getArg(0) ) ){
			$jsonArr =  $this->{$controller->getArg(0)}() ;
		}
		#API session messages merge
		if( isset( $jsonArr['sesssion_template_message']) ){
			$_SESSION['template']['message'] = array_merge((array)$_SESSION['template']['message'], (array)$jsonArr['sesssion_template_message']);
		}
		if( $returnResults ){
			$jsonArr['messagesHTML'] = F::get()->Tpl()->drawMessages();
			die(''.json_encode((array)$jsonArr));
		}else{
			#Redirect to last know location
			F::get()->Tpl()->redirect($_SESSION['breadcrumbs'][0]);
		}
		
	}
	
	function tableClassDialog(){
		$decryptedArr = json_decode( F::get()->Crypt()->decrypt($_POST['key']), true );
		
		//#create session token for form validation
		$token = F::get()->Auth()->createSessionToken($_POST['key']);
		
		#submit to api
		$postVals 							 = array();
		$postVals['token']			 = $token;		

		return F::get()->APICaller()->submit('callTableClassMethod',
			array(
				'key'=>$_POST['key'], 
				'postdata'=>$postVals,
				'method'=>'edit'
				)
			);
		
	}
	
	function tableClassDialogPost(){
		//TODO send $_FILE array to api ?? 
		$postVals 							   = array();
		$postVals['datatypeVal']   = $_POST['datatypeVal'];
		$postVals['switch']			 	 = $_POST['tableClassAction'];		
		$decryptedArr = json_decode( F::get()->Crypt()->decrypt($_POST['key']), true );
		
		# Ajax submit check the session for tokens
		if( F::get()->Auth()->checkSessionToken($_POST['key'], $_POST['token']) ){
			$encodedReq = F::get()->APICaller()->encode(array(
				'key'=>$_POST['key'], 
				'postdata'=>$postVals,
				'method'=>'postInit'
				));
			return F::get()->API(API_KEY, $encodedReq, 'callTableClassMethod')->_returnArray();
		}else{
			F::get()->Tpl()->addMessage('Error', 'Access token is invalid', 'error');
		}
	}
	
}
?>
